package archer.framework.security.utils;

import archer.framework.security.ArcherSecurityModule;
import archer.framework.security.analog.AnalogContextHolder;
import archer.framework.security.token.Subject;
import archer.framework.security.token.Token;
import archer.framework.utils.ServletUtils;
import archer.framework.utils.ValidateUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author christ
 * @date 2016/5/10
 */
public class SubjectUtils {

    /**
     * 获得当前请求对应的用户对象
     *
     * @return
     */
    public static Subject getSubject() {

        return getSubject(ServletUtils.getCurrentRequest());
    }

    /**
     * 获得当前登录用户id
     *
     * @return
     */
    public static Object getCurrentUserId() {

        Subject subject = SubjectUtils.getSubject();

        if (ValidateUtils.isNotEmpty(subject)) {
            return subject.getUserId();
        }

        return null;
    }

    /**
     * 获得请求对应的用户对象
     *
     * @param request
     * @return
     */
    public static Subject getSubject(HttpServletRequest request) {

        Subject subject = getSubject(TokenUtils.getToken(request));
        if (subject == null) {
            return getAnalogSubject();
        }
        return subject;
    }

    /**
     * 更新用户对象
     *
     * @param subject
     */
    public static void updateSubject(Subject subject) {

        updateSubject(ServletUtils.getCurrentRequest(), subject);
    }

    /**
     * 更新用户对象
     *
     * @param request
     * @param subject
     */
    public static void updateSubject(HttpServletRequest request, Subject subject) {
        Token token = TokenUtils.getToken(request);
        if (token != null) {
            token.removeAttribute(ArcherSecurityModule.subjectTokenAttr);
            token.setAttribute(ArcherSecurityModule.subjectTokenAttr, subject);
            TokenUtils.getTokenManager().update(token);
        }
    }

    /**
     * 虚拟登录用户
     *
     * @return
     */
    private static Subject getAnalogSubject() {

        return getSubject(AnalogContextHolder.get());
    }

    public static Subject getSubject(Token token) {
        return token == null
                ? null
                : (Subject) token.getAttribute(ArcherSecurityModule.subjectTokenAttr);
    }

    /**
     * 绑定相关联的token
     *
     * @param subject
     */
    public static Token bindAssociatedToken(Subject subject) {

        return TokenUtils.createToken(subject);
    }

    /**
     * 销毁相关联的token
     */
    public static void invalidateAssociatedToken() {

        TokenUtils.invalidateToken();
    }

    public static void invalidateAssociatedToken(String tokenId) {

        TokenUtils.invalidateToken(tokenId);
    }

    /**
     * 销毁相关联的token
     *
     * @param request
     */
    public static void invalidateAssociatedToken(HttpServletRequest request) {

        TokenUtils.invalidateToken(request);
    }
}
